package com.such.kit.resource;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import com.such.kit.Logger;
import com.such.kit.resource.support.ReadResource;
import com.such.kit.string.StringCommons;
import com.such.kit.validate.ValidateCommons;

/**
 * @author SUCH
 * <pre>
 * ReadResourceBundle 是基于资源束实现的 properties 资源文件操作工具类，因此 {@link #resourceName} 只支持类名
 * 由于是基于资源束的实现，ReadResourceBundle 支持国际化文件读取
 * </pre>
 */
public class ReadResourceBundle extends ReadResource {

	/** resourceName：资源名 */
	private String resourceName;
	/** locale：语言 */
	private Locale locale;

	/**
	 * <pre>
	 * [参考 {@link #ReadResourceBundle(String, Locale)}]
	 * 
	 * locale 默认为系统语言
	 * </pre>
	 */
	public ReadResourceBundle(String resourceName) {
		int index = resourceName.lastIndexOf(".");
		String enlargeName = "";
		if (index > -1) {
			enlargeName = resourceName.substring(index + 1);
		}
		if ("properties".equals(enlargeName)) {
			resourceName = resourceName.substring(0, index);
		}

		this.resourceName = resourceName;
	}

	/**
	 * @param resourceName [参考 {@link #resourceName}]
	 * @param locale [参考 {@link #locale}]
	 */
	public ReadResourceBundle(String resourceName, Locale locale) {
		this(resourceName);
		this.locale = locale;
	}

	@Override
	public String getResourceName() {
		return this.resourceName;
	}

	@Override
	public List<String> getKeys() {
		List<String> keys = new ArrayList<String>();
		ResourceBundle resource = getResourceBundle();
		if (ValidateCommons.isNotEmpty(resource)) {
			Enumeration<String> keyEnumeration = resource.getKeys();
			while(keyEnumeration.hasMoreElements()) {
				keys.add(keyEnumeration.nextElement());
			}
		}
		return keys;
	}

	@Override
	public String getValue(String key) {
		ResourceBundle resource = getResourceBundle();
		String value = null;
		if (ValidateCommons.isNotEmpty(resource)) {
			try {
				value = resource.getString(key);
			} catch (java.util.MissingResourceException e) {
				Logger.info(ReadResourceBundle.class, StringCommons.merger("未在 [", this.resourceName, "] 中找到键 [", key, "] 对应的资源"));
			}
		}
		return value;
	}

	@Override
	public Map<String, String> getValues() {
		Map<String, String> values = new HashMap<String, String>();
		for (String key : getKeys()) {
			values.put(key, getValue(key));
		}
		return values;
	}

	private ResourceBundle getResourceBundle() {
		// ResourceBundle 已经对资源进行了缓存处理
		ResourceBundle resource = null;
		if (ValidateCommons.isEmpty(this.locale)) {
			resource = ResourceBundle.getBundle(this.resourceName);
		} else {
			resource = ResourceBundle.getBundle(this.resourceName, this.locale);
		}
		return resource;
	}

}
